package com.glacier.yuyuan.modules.admin.sys.web;

import cn.hutool.core.util.StrUtil;
import com.glacier.common.core.domain.Result;
import com.glacier.common.core.domain.form.ListWrapper;
import com.glacier.common.core.factory.TreeFactory;
import com.glacier.yuyuan.common.utils.SecurityUtils;
import com.glacier.yuyuan.common.web.BaseController;
import com.glacier.yuyuan.modules.admin.sys.domain.Menu;
import com.glacier.yuyuan.modules.admin.sys.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * date 2022-12-27 09:23
 * 菜单控制层
 *
 * @author glacier
 * @version 1.0.0
 */
@RequestMapping("${yuyuan.adminPath}/sys/menu")
@Controller
public class MenuController extends BaseController {

    private MenuService menuService;

    @Autowired
    public void setMenuService(MenuService menuService) {
        this.menuService = menuService;
    }

    @GetMapping("")
    public String list() {
        return "admin/sys/menu/menuList";
    }

    @ResponseBody
    @PostMapping("/data")
    public Result<List<Menu>> data(Menu menu) {
        List<Menu> list = menuService.findList(menu);
        return Result.ok("ok", list, list.size());
    }

    @ResponseBody
    @GetMapping("/tree")
    public List<Menu> tree(Menu menu) {
        return TreeFactory.buildTree(menuService.findList(menu));
    }

    @ResponseBody
    @GetMapping("/currentTree")
    public List<Menu> currentTree() {
        return TreeFactory.buildTree(menuService.findListByUserId(SecurityUtils.getCurrentUserId()));
    }

    @GetMapping("/form")
    public String form(Menu menu, Model model) {
        if (StrUtil.isNotBlank(menu.getId())) {
            menu = menuService.findById(menu.getId());
        }
        model.addAttribute("entity", menu);
        return "admin/sys/menu/menuForm";
    }

    @PostMapping("/save")
    @ResponseBody
    public Result<String> save(Menu menu) {
        menuService.save(menu);
        return Result.ok("操作成功！", "");
    }

    @ResponseBody
    @PostMapping("/del")
    public Result<String> del(ListWrapper<String> form) {
        menuService.batchDelete(form.getDatas());
        return Result.ok("操作成功", "");
    }
}
